package com.rem.shiro.eeShiro.my4Authorization;

import com.rem.shiro.eeShiro.my3CustAuthentication.TestShiroMD5;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

/**
 * 授权的方式：
 * 基于角色的访问控制
 * 基于资源的访问控制
 * <p>
 * <p>
 * 授权编程实现的方式
 * 编程式
 * 注解式
 * 标签式
 *
 * @author Rem
 * @date 2021-04-03
 */

public class CustRealm extends AuthorizingRealm {

    /**
     * 授权
     *
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        String principal = (String) principals.getPrimaryPrincipal();
        System.out.println("身份信息：" + principal);
        //根据身份信息   获取角色信息以及权限信息
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        //讲数据库查询出来的角色授权给对象
        simpleAuthorizationInfo.addRole("admin");
        simpleAuthorizationInfo.addRole("user");

        simpleAuthorizationInfo.addStringPermission("user:*:*");
        simpleAuthorizationInfo.addStringPermission("product:*:02");
        return simpleAuthorizationInfo;
    }

    /**
     * 认证
     *
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //在shiro中获取用户名
        String principal = (String) token.getPrincipal();
        System.out.println(principal);
        //根据身份信息查询数据库进行
        if ("zhangsan".equals(principal)) {
            //参数1 用户名 参数2 密码 参数3 realm的名称
            //用户输入的是明文  数据库查出来的密码是密文
            // SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo("zhangsan", "202cb962ac59075b964b07152d234b70", this.getName());

            //参数1 用户名 参数2 密码 参数3随机盐 参数4 realm的名称
            SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(
                    "zhangsan",
                    "c6ea0b57046a51a73d80c642944efd3e",
                    ByteSource.Util.bytes(TestShiroMD5.SALT),
                    this.getName());
            return simpleAuthenticationInfo;
        }


        return null;
    }
}
